<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Queries\DealerQuery;
use App\Http\Requests\Api\DealerRequest;
use App\Models\AreaCode;
use App\Models\Dealer;
use Illuminate\Database\Eloquent\Builder;

class DealerController extends Controller
{
    public function index(DealerRequest $request, DealerQuery $query)
    {
        $area_code = AreaCode::where('area_name', $request->city)->where('area_level', 2)->first();
        if (is_null($area_code)) {
            return $this->failed('unfound-area-code');
        }
        $adcode = substr($area_code->area_code, 0, 4);
        $query = $query->where('online', true)->where('area_code', 'like', $adcode . '%');
        if ($request->vehicle_series_id) {
            $query = $query->whereHas('series', function (Builder $query) use ($request) {
                $query->where('vehicle_series.id', $request->vehicle_series_id);
            });
        }
        $dealers = $query->get()->toArray();

        if (!empty($dealers)) {
            $to = '';
            foreach ($dealers as &$dealer) {
                $to .= $dealer['lat'] . ',' . $dealer['lng'] . ';';
                $dealer['intro'] = $dealer['name'] . ' ';
                //普通店不显示普通点几个字样
                $dealer['level_ch'] = $dealer['level'] == 2 ? '' : Dealer::$levelMap[$dealer['level']];
                $dealer['intro'] .= $dealer['level'] == 2 ? '' : $dealer['level_ch'] . ' ';
            }
            if (!empty($request->location)) {
                $to = rtrim($to, ';');
                $result = app('App\Services\MapService')->distance($request->location, $to);
                $i = 0;
                $elements = $result['rows'][0]['elements'];
                foreach ($dealers as &$dealer) {
                    $dealer['distance'] = $elements[$i]['distance'];
                    $dealer['duration'] = $elements[$i]['duration'];
                    $dealer['intro'] .= round($dealer['distance'] / 1000, 2) . 'km';
                    unset($dealer['created_at']);
                    unset($dealer['updated_at']);
                    $i++;
                }
                $sort = array_column($dealers, 'distance');
                array_multisort($sort, SORT_ASC, $dealers);
            }
        }
        return $this->success($dealers);
    }
}
